import 'package:hive/hive.dart';

part 'user_settings.g.dart';

/// 播放模式枚举
enum PlayMode {
  /// 顺序播放
  sequence,
  /// 随机播放
  shuffle,
  /// 单曲循环
  repeatOne,
  /// 列表循环
  repeatAll,
}

/// 主题模式枚举
enum ThemeMode {
  /// 跟随系统
  system,
  /// 浅色主题
  light,
  /// 深色主题
  dark,
}

/// 音质设置枚举
enum AudioQuality {
  /// 标准音质
  standard,
  /// 高音质
  high,
  /// 无损音质
  lossless,
}

/// 用户设置数据模型类
/// 包含用户的个性化设置和偏好
@HiveType(typeId: 5)
class UserSettings {
  /// 设置ID
  @HiveField(0)
  final String id;

  /// 主题模式
  @HiveField(1)
  final ThemeMode themeMode;

  /// 音量设置（0.0-1.0）
  @HiveField(2)
  final double volume;

  /// 播放模式
  @HiveField(3)
  final PlayMode playMode;

  /// 是否启用随机播放
  @HiveField(4)
  final bool shuffleEnabled;

  /// 重复模式
  @HiveField(5)
  final String repeatMode;

  /// 均衡器预设
  @HiveField(6)
  final String equalizerPreset;

  /// 是否启用淡入淡出效果
  @HiveField(7)
  final bool crossfadeEnabled;

  /// 淡入淡出时长（毫秒）
  @HiveField(8)
  final int crossfadeDuration;

  /// 音质设置
  @HiveField(9)
  final AudioQuality audioQuality;

  /// 是否启用歌词显示
  @HiveField(10)
  final bool lyricsEnabled;

  /// 是否启用睡眠定时器
  @HiveField(11)
  final bool sleepTimerEnabled;

  /// 睡眠定时器时长（分钟）
  @HiveField(12)
  final int sleepTimerDuration;

  /// 是否启用震动反馈
  @HiveField(13)
  final bool hapticFeedbackEnabled;

  /// 是否启用锁屏控制
  @HiveField(14)
  final bool lockScreenControlEnabled;

  /// 更新时间
  @HiveField(15)
  final DateTime updatedAt;

  /// 构造函数
  UserSettings({
    required this.id,
    this.themeMode = ThemeMode.system,
    this.volume = 1.0,
    this.playMode = PlayMode.sequence,
    this.shuffleEnabled = false,
    this.repeatMode = 'none',
    this.equalizerPreset = 'normal',
    this.crossfadeEnabled = false,
    this.crossfadeDuration = 3000,
    this.audioQuality = AudioQuality.high,
    this.lyricsEnabled = true,
    this.sleepTimerEnabled = false,
    this.sleepTimerDuration = 30,
    this.hapticFeedbackEnabled = true,
    this.lockScreenControlEnabled = true,
    required this.updatedAt,
  });

  /// 创建默认设置
  factory UserSettings.defaultSettings() {
    return UserSettings(
      id: 'default',
      updatedAt: DateTime.now(),
    );
  }

  /// 从JSON创建UserSettings对象
  factory UserSettings.fromJson(Map<String, dynamic> json) {
    return UserSettings(
      id: json['id'] as String,
      themeMode: ThemeMode.values.firstWhere(
        (e) => e.name == json['theme_mode'],
        orElse: () => ThemeMode.system,
      ),
      volume: (json['volume'] as num).toDouble(),
      playMode: PlayMode.values.firstWhere(
        (e) => e.name == json['play_mode'],
        orElse: () => PlayMode.sequence,
      ),
      shuffleEnabled: json['shuffle_enabled'] is int 
          ? (json['shuffle_enabled'] as int) == 1 
          : json['shuffle_enabled'] as bool, // 处理int和bool两种格式
      repeatMode: json['repeat_mode'] as String,
      equalizerPreset: json['equalizer_preset'] as String,
      crossfadeEnabled: json['crossfade_enabled'] is int 
          ? (json['crossfade_enabled'] as int) == 1 
          : json['crossfade_enabled'] as bool? ?? false, // 处理int和bool两种格式
      crossfadeDuration: json['crossfade_duration'] as int? ?? 3000,
      audioQuality: AudioQuality.values.firstWhere(
        (e) => e.name == json['audio_quality'],
        orElse: () => AudioQuality.high,
      ),
      lyricsEnabled: json['lyrics_enabled'] is int 
          ? (json['lyrics_enabled'] as int) == 1 
          : json['lyrics_enabled'] as bool? ?? true, // 处理int和bool两种格式
      sleepTimerEnabled: json['sleep_timer_enabled'] is int 
          ? (json['sleep_timer_enabled'] as int) == 1 
          : json['sleep_timer_enabled'] as bool? ?? false, // 处理int和bool两种格式
      sleepTimerDuration: json['sleep_timer_duration'] as int? ?? 30,
      hapticFeedbackEnabled: json['haptic_feedback_enabled'] is int 
          ? (json['haptic_feedback_enabled'] as int) == 1 
          : json['haptic_feedback_enabled'] as bool? ?? true, // 处理int和bool两种格式
      lockScreenControlEnabled: json['lock_screen_control_enabled'] is int 
          ? (json['lock_screen_control_enabled'] as int) == 1 
          : json['lock_screen_control_enabled'] as bool? ?? true, // 处理int和bool两种格式
      updatedAt: DateTime.fromMillisecondsSinceEpoch(json['updated_at'] as int),
    );
  }

  /// 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'theme_mode': themeMode.name,
      'volume': volume,
      'play_mode': playMode.name,
      'shuffle_enabled': shuffleEnabled ? 1 : 0, // 将bool转换为int
      'repeat_mode': repeatMode,
      'equalizer_preset': equalizerPreset,
      'crossfade_enabled': crossfadeEnabled ? 1 : 0, // 将bool转换为int
      'crossfade_duration': crossfadeDuration,
      'audio_quality': audioQuality.name,
      'lyrics_enabled': lyricsEnabled ? 1 : 0, // 将bool转换为int
      'sleep_timer_enabled': sleepTimerEnabled ? 1 : 0, // 将bool转换为int
      'sleep_timer_duration': sleepTimerDuration,
      'haptic_feedback_enabled': hapticFeedbackEnabled ? 1 : 0, // 将bool转换为int
      'lock_screen_control_enabled': lockScreenControlEnabled ? 1 : 0, // 将bool转换为int
      'updated_at': updatedAt.millisecondsSinceEpoch,
    };
  }

  /// 复制并修改部分属性
  UserSettings copyWith({
    String? id,
    ThemeMode? themeMode,
    double? volume,
    PlayMode? playMode,
    bool? shuffleEnabled,
    String? repeatMode,
    String? equalizerPreset,
    bool? crossfadeEnabled,
    int? crossfadeDuration,
    AudioQuality? audioQuality,
    bool? lyricsEnabled,
    bool? sleepTimerEnabled,
    int? sleepTimerDuration,
    bool? hapticFeedbackEnabled,
    bool? lockScreenControlEnabled,
    DateTime? updatedAt,
  }) {
    return UserSettings(
      id: id ?? this.id,
      themeMode: themeMode ?? this.themeMode,
      volume: volume ?? this.volume,
      playMode: playMode ?? this.playMode,
      shuffleEnabled: shuffleEnabled ?? this.shuffleEnabled,
      repeatMode: repeatMode ?? this.repeatMode,
      equalizerPreset: equalizerPreset ?? this.equalizerPreset,
      crossfadeEnabled: crossfadeEnabled ?? this.crossfadeEnabled,
      crossfadeDuration: crossfadeDuration ?? this.crossfadeDuration,
      audioQuality: audioQuality ?? this.audioQuality,
      lyricsEnabled: lyricsEnabled ?? this.lyricsEnabled,
      sleepTimerEnabled: sleepTimerEnabled ?? this.sleepTimerEnabled,
      sleepTimerDuration: sleepTimerDuration ?? this.sleepTimerDuration,
      hapticFeedbackEnabled: hapticFeedbackEnabled ?? this.hapticFeedbackEnabled,
      lockScreenControlEnabled: lockScreenControlEnabled ?? this.lockScreenControlEnabled,
      updatedAt: updatedAt ?? DateTime.now(),
    );
  }

  /// 获取主题模式的显示名称
  String get themeModeDisplayName {
    switch (themeMode) {
      case ThemeMode.system:
        return '跟随系统';
      case ThemeMode.light:
        return '浅色主题';
      case ThemeMode.dark:
        return '深色主题';
    }
  }

  /// 获取播放模式的显示名称
  String get playModeDisplayName {
    switch (playMode) {
      case PlayMode.sequence:
        return '顺序播放';
      case PlayMode.shuffle:
        return '随机播放';
      case PlayMode.repeatOne:
        return '单曲循环';
      case PlayMode.repeatAll:
        return '列表循环';
    }
  }

  /// 获取音质设置的显示名称
  String get audioQualityDisplayName {
    switch (audioQuality) {
      case AudioQuality.standard:
        return '标准音质';
      case AudioQuality.high:
        return '高音质';
      case AudioQuality.lossless:
        return '无损音质';
    }
  }

  /// 获取音量百分比
  int get volumePercentage => (volume * 100).round();

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;
    return other is UserSettings && other.id == id;
  }

  @override
  int get hashCode => id.hashCode;

  @override
  String toString() {
    return 'UserSettings(id: $id, themeMode: $themeMode, volume: $volume, playMode: $playMode)';
  }
}